package com.atguigu.gulimall.gulimallauthserver.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.gulimallauthserver.feign.MemberFeignService;
import com.atguigu.gulimall.gulimallauthserver.feign.ThridPartFeignService;
import com.atguigu.gulimall.gulimallauthserver.vo.UserLoginVo;
import com.atguigu.common.vo.UserMemberVo;
import com.atguigu.gulimall.gulimallauthserver.vo.UserRegistVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class LoginController {

    /**
     * 发送一个请求  直接跳转到一个页面
     *
     * springMvc viewController
     * @return
     */
    @Resource
    ThridPartFeignService thridPartFeignService;
    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Resource
    MemberFeignService memberFeignService;

    @GetMapping("/sms/sendcode")
    public R sendCode(@RequestParam("phone") String phone){
        //todo 1、接口防刷

        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if(redisCode!=null){
            long l = Long.parseLong(redisCode.split("_")[1]);
            if(System.currentTimeMillis()-l<60000){
                return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(),BizCodeEnume.SMS_CODE_EXCEPTION.getMessage());
            }
        }

        //2、验证码的再次校验。 redis: 存key-phone  value-code
        String code = UUID.randomUUID().toString().substring(0, 6)+"_"+System.currentTimeMillis();

        //redis 缓存验证码
        stringRedisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone,code,5, TimeUnit.MINUTES);
        thridPartFeignService.sendCode(phone, code.substring(0,6));
        return R.ok();
    }

    @PostMapping("/regist")
    public String regist(@Valid UserRegistVo vo, BindingResult result, RedirectAttributes redirectAttributes){
        if(result.hasErrors()){
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://outh.gulimall.com/regist.html";
        }
        //真正注册
        //校验验证码
        String code = vo.getCode();
        String phone = vo.getPhone();
        String s = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if(StringUtils.isNotBlank(s)){
            if(code.equals(s.split("_")[0])){
                //删除redis 验证码
                stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
                //验证码通过
                R regist = memberFeignService.regist(vo);
                if(regist.getCode()==0){
                    //成功
                    return "redirect:http://outh.gulimall.com/login.html";
                }else {
                    HashMap<String, String> map = new HashMap<>();
                    map.put("msg",regist.getData(new TypeReference<String>(){}));
                    redirectAttributes.addAttribute("errors",map);
                    return "redirect:http://outh.gulimall.com/regist.html";
                }
            }else {
                HashMap<String, String> errors = new HashMap<>();
                errors.put("code","验证码错误");
                return "redirect:http://outh.gulimall.com/regist.html";
            }
        }else {
            HashMap<String, String> errors = new HashMap<>();
            errors.put("code","验证码错误");
            return "redirect:http://outh.gulimall.com/regist.html";
        }
    }

    @PostMapping("/login")
    public String login(UserLoginVo vo, HttpSession session){
        R login = memberFeignService.login(vo);
        if(login.getCode()==0){
            UserMemberVo data = login.getData(new TypeReference<UserMemberVo>() {
            });
            System.err.println(data);
            session.setAttribute(AuthServerConstant.LOGIN_USER,data);
            return "redirect:http://gulimall.com";
        }else {
            HashMap<String, String> map = new HashMap<>();
            String data = login.getData(new TypeReference<String>() {
            });
            System.err.println(data);
            map.put("msg",data);
//            attributes.addAttribute("errors",map);
            return "redirect:http://outh.gulimall.com/login.html";
        }
    }

    @GetMapping("/login.html")
    public String login(HttpSession session){
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if(attribute==null){
            return "login";
        }else {
            return "redirect:http://gulimall.com";
        }
    }
}
